package com.helloUIBinder.service;

import com.helloUIBinder.model.BlogPost;
import com.helloUIBinder.repository.BlogPostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BlogPostManager {

    @Autowired
    BlogPostRepository blogPostRepository;

    public BlogPost saveBlogPost(BlogPost blogPost) {
        return blogPostRepository.save(blogPost);
    }

    public List<BlogPost> getAllBlogPosts() {
        return blogPostRepository.findAll();
    }

    public Long size() {
        return blogPostRepository.count();
    }


    public BlogPost findBlogPostById(long id) {
        return blogPostRepository.findOne(id);
    }

    public List<BlogPost> findAllBlogPostsByPage(Integer pageNumber, Integer pageSize, String sortColumn, Sort.Direction direction) {
        Pageable pageable;
        if(sortColumn == null || direction == null){
            pageable = new PageRequest(pageNumber, pageSize);
        }else{
            pageable = new PageRequest(pageNumber, pageSize, direction, sortColumn);
        }
        return blogPostRepository.findAll(pageable).getContent();
    }

    public void deleteBlogPost(BlogPost blogPost) {
        blogPostRepository.delete(blogPost);
    }

    public void deleteBlogPostById(Long id) {
        blogPostRepository.delete(id);
    }

}
